package com.gift.recommendation.config;


import com.auth0.jwt.exceptions.TokenExpiredException;
import com.gift.recommendation.Base.MyException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author zzh <2658137258@qq.com>
 * @date 2022/11/4
 */

/**
 * 拦截器拦截后的实现类
 */
@Slf4j
public class UserLoginInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");

        //当方法设置为OPTIONS预检时，直接放行
        if("OPTIONS".equals(request.getMethod().toUpperCase())){
            return true;
        }

        //如果方法上有此注解，直接放行
        try {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            if(method.isAnnotationPresent(TokenPass.class)){
                TokenPass passToken = method.getAnnotation(TokenPass.class);
                if (passToken.required()){
                    return true;
                }
            }
        }catch (Exception e){
            log.info("跳过检查");
        }

        //token不存在
        if (token==null || token.equals("")){
            throw new RuntimeException("token不存在");
        }

        //验证token是否正确
        try {
            boolean sub = TokenConfig.verify(token);
            return true;
        }catch (TokenExpiredException e){
            throw new RuntimeException("token已过期");
        }catch (Exception e){
            throw new RuntimeException("token不正确，请不要通过非法手段创建token");
        }
    }
}
